<template>
  <header class="header">
    <h1>todos</h1>
    <input
      id="toggle-all"
      :disabled="list.length == 0"
      v-model="isAll"
      class="toggle-all"
      type="checkbox"
    />
    <label for="toggle-all"></label>
    <input
      @keydown.enter="add"
      v-model.trim="taskname"
      class="new-todo"
      placeholder="输入任务名称-回车确认"
      autofocus
    />
  </header>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      taskname: ''
    }
  },
  methods: {
    add () {
      // 非空判断
      if (this.taskname.length == 0) return alert('输入不能为空')

      // 子传父
      this.$emit('addTask', this.taskname)

      // 添加完成后清空文本框
      this.taskname = ''
    }
  },
  computed: {
    isAll: {
      set (val) {
        // 根据全选框的状态控制小选框
        this.list.forEach(item => (item.isDone = val))
      },
      get () {
        // 当数据长度为0时， isAll 不亮
        if (this.list.length == 0) return false
        // 返回所有小选框=true
        return this.list.every(item => item.isDone)
      }
    }
  }
}
</script>
